package main

import (
	"bufio"
	"catfish/purifier"
	"flag"
	"fmt"
	"github.com/astaxie/beego/logs"
	"os"
	"strings"
	"time"
)

var (
	CatfishServerAliyun = "218.244.150.208:80"
	CatfishServer       = "127.0.0.1:8080"

	EcareLoger     *logs.BeeLogger
	BrowserLoger   *logs.BeeLogger
	MsgAssertLoger *logs.BeeLogger

	BrowserInterval = 60
	BrowserTimes    = 300
)

func init() {
	EcareLoger = logs.NewLogger(10000)
	EcareLoger.SetLogger("console", "")
	EcareLoger.SetLogger("file", `{"filename":"log/ecare.log"}`)

	BrowserLoger = logs.NewLogger(10000)
	BrowserLoger.SetLogger("console", "")
	BrowserLoger.SetLogger("file", `{"filename":"log/browser.log"}`)

	MsgAssertLoger = logs.NewLogger(10000)
	MsgAssertLoger.SetLogger("console", "")
	MsgAssertLoger.SetLogger("file", `{"filename":"log/msgassert.log"}`)

	purifier.SetLogger(EcareLoger)
}

func runEcareDevice(id int, email, catfishServer string, msgCache *AssertCache) {
	// Create One Ecare Device
	ecare := EcareDevice{Id: id, RH: 55, Pm25: 20, Tmp: 28.533, UserInfo: email, CatfishServer: catfishServer}
	ecare.SetMsgCache(msgCache)
	ecare.Serve()
}

func runBrowser(id int, email, psk string, msgCache *AssertCache) {
	ecare := EcareDevice{Id: id, RH: 55, Tmp: 28.533, UserInfo: email}
	browser := PesudoBrowser{User: email, Pass: psk, DeviceMac: ecare.Whoami()}
	browser.SetMsgCache(msgCache)
	// wait for device to register or online
	// and avoid browser all start at the same time.
	<-time.After(time.Duration(id+5) * time.Second)

	browser.Work()
}

// Device and Browser:
/*
Local:

  Ecare & PesudoBrowser
./hookfish -A no -E thyang@imaginevision-tech.com@12oHYu2EXTuq -I 1 -N 1 -L console -b yes -p thyang
./hookfish -A no -E thyang@imaginevision-tech.com@12oHYu2EXTuq -I 1 -N 1 -L file -b yes -p thyang -bi 5

  Ecare Only:
./hookfish -A no -E thyang@imaginevision-tech.com@12oHYu2EXTuq -I 1 -N 1 -L console


Remote Aliyun thyang:

  Ecare & PesudoBrowser
./hookfish -E thyang@imaginevision-tech.com@1wDu2dOQ3Wh -I 1 -N 10 -L file -b yes -p thyang
./hookfish -E thyang@imaginevision-tech.com@1wDu2dOQ3Wh -I 1 -N 10 -L file -b yes -p thyang -bi 5


  Ecare Only:
./hookfish -E thyang@imaginevision-tech.com@1wDu2dOQ3Wh -I 1 -N 1

*/
func main() {

	aliyun := flag.String("A", "yes", "\tAliyunServer Addr: {yes,no, 218.244.150.208:80}")
	userInfo := flag.String("E", "", "\tEcareCode, eg.: thyang@imaginevision-tech.com@12oHYu2EXTuq (Must)")
	idDev := flag.Int("I", 1, "\tDevice Id(first device id)")
	numDev := flag.Int("N", 1, "\tDevice Num")

	startBrowser := flag.String("b", "no", "\tBrowser Robots {yes,no} (Optional)")
	email := ""
	psk := flag.String("p", "", "\tBrowser Password")

	interval := flag.Int("bi", 60, "\tBrowser request interval(request every n second)")
	times := flag.Int("btimes", 300, "\tBrowser request times(/info + /status)")

	logToFile := flag.String("L", "", "\tLog {console,file,both}")

	flag.Parse()

	if *logToFile == "file" {
		EcareLoger.DelLogger("console")
		BrowserLoger.DelLogger("console")
		MsgAssertLoger.DelLogger("console")
	} else if *logToFile == "console" {
		EcareLoger.DelLogger("file")
		BrowserLoger.DelLogger("file")
		MsgAssertLoger.DelLogger("file")
	} else {
		// both
	}

	if *userInfo == "" {
		flag.PrintDefaults()
		os.Exit(2)
	}

	if *aliyun == "yes" {
		CatfishServer = CatfishServerAliyun
	} else if *aliyun == "no" {
		// pass
	} else {
		CatfishServer = *aliyun
	}
	UrlReSet()

	fmt.Printf("CatfishServer:%s\n", CatfishServer)
	fmt.Printf("StartDevice: %d\n", *numDev)
	fmt.Printf("EcareCode:%s\n", *userInfo)

	if *startBrowser == "yes" {
		// extract email from EcareCode
		idx := strings.LastIndex(*userInfo, "@")
		email = (*userInfo)[:idx]
		if email == "" || *psk == "" {
			fmt.Println("Browser need: Email,Psk")
			flag.PrintDefaults()
			os.Exit(2)
		}

		BrowserInterval = *interval
		BrowserTimes = *times

		fmt.Printf("startBrowserWith,Email:%s Psk:%s Interval:%d(s) Times:%d\n",
			email, *psk, BrowserInterval, BrowserTimes)
	}

	// Run Device And Browser
	total := *numDev
	var msgCache *AssertCache
	for i := *idDev; i <= total; i++ {
		if *startBrowser == "yes" {
			msgCache = NewAssertCache(fmt.Sprintf("Go_%d", i))
		} else {
			msgCache = nil
		}
		go runEcareDevice(i, *userInfo, CatfishServer, msgCache)

		if *startBrowser == "yes" {
			go runBrowser(i, email, *psk, msgCache)
		}
	}

	reader := bufio.NewReader(os.Stdin)
	for {
		input, _ := reader.ReadString('\n')
		fmt.Printf("Input Is : %v", input)
		if input == "q\n" {
			fmt.Println("Done")
			break
		}
	}
}
